﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;

namespace Web7.Mvc.ViewEngines
{
    public interface IViewEngineServiceProvider
    {
        ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache);
        ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache);
    }

    public class ViewEngineServiceProvider : IViewEngineServiceProvider
    {
        private readonly IEnumerable<IViewEngineProvider> _viewEngineProviders;

        private readonly IViewEngine _nullEngines = new ViewEngineCollectionWrapper(Enumerable.Empty<IViewEngine>());

        public ViewEngineServiceProvider(IEnumerable<IViewEngineProvider> viewEngineProviders)
        {
            _viewEngineProviders = viewEngineProviders;
        }

        public ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
        {
            var viewEngines = _nullEngines;

            var engines = Enumerable.Empty<IViewEngine>();
            engines = engines.Concat(_viewEngineProviders.Select(vep => vep.CreateViewEngine(new CreateViewEngineParams())));

            viewEngines = new ViewEngineCollectionWrapper(engines);

            return viewEngines.FindPartialView(controllerContext, partialViewName, useCache);
        }

        public ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
        {
            var viewEngines = _nullEngines;

            var engines = Enumerable.Empty<IViewEngine>();
            engines = engines.Concat(_viewEngineProviders.Select(vep => vep.CreateViewEngine(new CreateViewEngineParams())));

            viewEngines = new ViewEngineCollectionWrapper(engines);

            return viewEngines.FindView(controllerContext, viewName, masterName, useCache);
        }

        private IViewEngine BareEngines()
        {
            return null;
        }

        public void ReleaseView(ControllerContext controllerContext, IView view)
        {
            throw new NotImplementedException();
        }
    }
}
